<?php
set_time_limit(0);

include_once (dirname(__FILE__).'/config/database.php');
include_once (dirname(__FILE__).'/class/Log.inc');
include_once (dirname(__FILE__).'/class/Mysql/Exception.inc');
include_once (dirname(__FILE__).'/class/Mysql.inc');

define('LOCK_FILE', dirname(__FILE__).'/lock/countUser.lock');
define('LOG_LEVEL', 'ERROR');

$LogFile = dirname(__FILE__).'/log/countUser'.date('Y.m.d').'.log';

$Log = new Zw_Log();
$Log->setCurrLogLevel(LOG_LEVEL);
$Log->setLogFile($LogFile);

$handle = fopen(LOCK_FILE, 'w+');
if(!flock($handle, LOCK_EX|LOCK_NB)){
	$Log->write('进程已经启动，请不要重复启动');
	exit();
}

$GmDb = new Zw_Mysql();
$GmDb->setLog($Log);
$GmDb->connect($gmDatabaseHost, $gmDatabaseUsername, $gmDatabasePassword, $gmDatabaseName);

$GameDb = new Zw_Mysql();
$GameDb->setLog($Log);
$count = 0;
$a=array();
	try {
		$sql = "
			select
				e.`ipAddress`,
				c.`databaseName`,
				g.`operatorFlag`

			from

				`t_data_game_area` c

			left join
				`t_data_server_ip` d
			on
				c.`serverId` = d.`serverId`
			left join
				`t_data_ip` e
			on
				d.`ipId` = e.`ipId`
			left join
				`t_cfg_ip_type` f
			on
				e.`ipTypeId` = f.`ipTypeId`
			left JOIN
				`t_data_operator` g
			on
				g.`operatorId` = c.`operatorId`
			where
				c.`databaseName` != 'styx_cn_sogou_997'
			and
				 c.`databaseName` != 'styx_cn_sogou_998'
			and
				c.`databaseName` != 'styx_cn_sogou_999'
			and
				f.`isDefault` = 1
			and
				g.`operatorFlag` = 'cn_nw186'
			group by c.`databaseName`
		";
		$IpArray = $GmDb->getArray($sql);

		foreach ($IpArray as $k1 => $v1) {
			$a[$v1['operatorName']] = 0;
		}

		foreach ($IpArray as $k1 => $v1) {
			$GameDb->connect($v1['ipAddress'], $gameDatabaseUsername, $gameDatabasePassword, $v1['databaseName']);

			$sql = "
				select b.operator,b.username,a.CharName,a.viplevel,a.Gold from t_char a LEFT JOIN t_user b on a.uid = b.userid where a.gift >= 2000 and vipLevel = 0
					";

			$result = $GameDb->getArray($sql);
//			$Log->write("查询-".json_encode($result), 'ERROR');

			foreach($result as $user){
				file_put_contents($LogFile, "{$user['operator']}\t{$user['username']}\t{$user['CharName']}\t{$user['viplevel']}\t{$user['Gold']}\n", FILE_APPEND);
			}
		}

	}

	catch(Zw_Mysql_Exception $e) {
		$Log->write('数据库错误', 'ERROR');
	}
	catch(Exception $e) {
		$Log->write('系统错误', 'ERROR');
	}
